package org.dftproject.pgv.ui;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.util.Date;
import java.util.Properties;

import org.dftproject.genesis.core.collections.Collection;
import org.dftproject.genesis.core.collections.CollectionManager;
import org.dftproject.genesis.ui.Activator;
import org.dftproject.genesis.ui.collections.ICollectionHandler;
import org.dftproject.genesis.ui.figures.HyperlinkFigure;
import org.dftproject.genesis.ui.figures.IHyperlinkListener;
import org.dftproject.genesis.ui.figures.TooltipLabel;
import org.dftproject.genesis.ui.figures.UniformSizeContainer;
import org.dftproject.genesis.ui.figures.UniformSizeGroup;
import org.dftproject.genesis.ui.pages.PageManager;
import org.dftproject.pgv.core.cache.CacheManager;
import org.dftproject.pgv.core.racp.PGVGedcom;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.MarginBorder;
import org.eclipse.draw2d.ToolbarLayout;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;

public class GedcomFigure extends Figure {

	private final PGVGedcom gedcom;
	
	public GedcomFigure(final PGVGedcom gedcom, UniformSizeGroup linkGroup) {
		this.gedcom = gedcom;
		
		ToolbarLayout layout = new ToolbarLayout(true);
		layout.setStretchMinorAxis(true);
		setLayoutManager(layout);

		setBorder(new MarginBorder(3, 5, 3, 5));

		HyperlinkFigure link = new HyperlinkFigure(gedcom.getTitle());
		link.setToolTip(new TooltipLabel(gedcom.getGedcomId()));
		link.setAlwaysUnderline(false);
		link.addHyperlinkListener(new IHyperlinkListener() {

			public void linkActivated(Object data, int stateMask) {
				Properties props = new Properties();
				props.put("url", gedcom.getUrl());
				props.put("username", gedcom.getSession().getUsername());
				props.put("password", gedcom.getSession().getPassword());
				props.put("gedcomId", gedcom.getGedcomId());
				
				ByteArrayOutputStream os = new ByteArrayOutputStream();
				try {
					props.store(os, null);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Collection collection = new Collection("pgv:" + gedcom.getUrl(), gedcom.getTitle(), gedcom.getUrl(), "org.dftproject.pgv", os.toString(), new Date());
				collection = CollectionManager.getDefault().addCollection(collection);
				CacheManager.getDefault().clearAllRecords(gedcom.getUrl(), gedcom.getGedcomId());
				
				IWorkbench workbench = PlatformUI.getWorkbench();
				IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
				PageManager.getDefault().openPage(window.getActivePage(), new PGVPageInput(gedcom), PGVPage.ID, true, false);
			}
			
		});
		add(new UniformSizeContainer(link, linkGroup, false));
	}
	
	protected static ICollectionHandler getCollectionHandler(Collection collection) {
		String type = collection.getType();

		IExtensionRegistry registry = Platform.getExtensionRegistry();
		IExtensionPoint extensionPoint = registry.getExtensionPoint(Activator.ID, Activator.COLLECTION_HANDLERS_EXTENSION_POINT);
		IExtension[] extensions = extensionPoint.getExtensions();
		for (IExtension extension : extensions) {
			IConfigurationElement[] configElements = extension.getConfigurationElements();
			for (IConfigurationElement configElement : configElements) {
				if (type.equals(configElement.getAttribute("type"))) {
					try {
						Object instance = configElement.createExecutableExtension("class");
						if (instance instanceof ICollectionHandler)
							return (ICollectionHandler) instance;
					} catch (CoreException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

		return null;
	}
	
	protected static Image getCollectionIcon(Collection collection) {
		String type = collection.getType();

		IExtensionRegistry registry = Platform.getExtensionRegistry();
		IExtensionPoint extensionPoint = registry.getExtensionPoint(Activator.ID, Activator.COLLECTION_HANDLERS_EXTENSION_POINT);
		IExtension[] extensions = extensionPoint.getExtensions();
		for (IExtension extension : extensions) {
			IConfigurationElement[] configElements = extension.getConfigurationElements();
			for (IConfigurationElement configElement : configElements) {
				if (type.equals(configElement.getAttribute("type"))) {
					String iconPath = configElement.getAttribute("icon");
					String plugin = extension.getNamespaceIdentifier();
					return getImageFromPlugin(plugin, iconPath);
				}
			}
		}

		return null;
	}

	protected static Image getImageFromPlugin(String plugin, String iconPath) {		
		Image image = null;
		try {
			ImageDescriptor imageDescriptor = ImageDescriptor.createFromURL(new URL(Platform.getBundle(plugin).getEntry("/"), iconPath));
			image = imageDescriptor.createImage();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return image;
	}
	
	protected String stringFromDate(Date date) {
		if (date == null)
			return "";
		return DateFormat.getDateInstance().format(date);
	}

	public PGVGedcom getPGVGedcom() {
		return gedcom;
	}

}
